package com.haoyeteng.sxbd.core.mongodb;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.BasicDBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

/**
 * mongo文件写出
 * 
 * @author 理想
 *
 */
public class MongoFileWriter {

	@Autowired
	MongoTemplate mongoTemplate;

	public boolean toWrite(InputStream in, String fileName, String fileId, String contentType) throws IOException {
		GridFS gridFs = new GridFS(mongoTemplate.getDb());
		GridFSInputFile gridFsInput = gridFs.createFile(in);
		gridFsInput.setFilename(fileName);
		gridFsInput.setId(fileId);
		gridFsInput.setContentType(contentType);
		gridFsInput.save();
		BasicDBObject query = new BasicDBObject();
		query.put("filename", fileName);
		query.put("_id", fileId);
		GridFSDBFile gridFSDBFile = gridFs.findOne(query);
		if (null != gridFSDBFile) {
			return true;
		}
		return false;
	}

	public void toDelete(String fileId) throws IOException {
		GridFS gridFs = new GridFS(mongoTemplate.getDb());
		BasicDBObject query = new BasicDBObject();
		query.put("_id", fileId);

		GridFSDBFile gridFSDBFile = gridFs.findOne(query);
		if (null == gridFSDBFile) {
			return;
		}
		gridFs.remove(gridFSDBFile);
	}

}